package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {


    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R submitOrder(@RequestBody Orders orders){
        return ordersService.submitOrder(orders);
    }

    @GetMapping("/userPage")
    public R queryPage(Integer page,Integer pageSize){

        Page<Orders> pageInfo = new Page<>(page,pageSize);
        ordersService.page(pageInfo);
        List<Orders> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();

        //List<Orders>   List<OrderDto>
        List<OrdersDto> collect = records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtil.copyProperties(orders, ordersDto);

            //订单明细
            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getOrderId, ordersDto.getNumber());
            List<OrderDetail> details = orderDetailService.list(qw);
            ordersDto.setOrderDetails(details);
            return ordersDto;
        }).collect(Collectors.toList());
        Map map = new HashMap();
        map.put("total",total);
        map.put("records",collect);

        return R.success(map);
    }


    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, Long number,
                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date endTime){

        System.out.println(page);
        return null;
    }
}
